<?php
/**
 * Easthv Zend Framework Project
 *
 *
 * LICENSE:
 *
 * @category   Zend
 * @package    Zend_Easthv
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
*/

/**
 * Google Chart Create Class
 *
 * @category   Zend
 * @package    Zend_Easthv
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
 * @deprecated
 */
class Zend_Easthv_Gchart
{
    /**
     * @staticvar array  Google Chart graphs save paths 
     */
    public static $savepath = array(
        'inline' => '',    
        'small' => '',    
        'medium' => '',    
        'large' => '',    
    );
    
    /**
     * @staticvar string  Google Chart API URL
     */
    protected static $_api = 'http://chart.apis.google.com/chart';

    /**
     * Create y axis
     *
     * @access public
     * @param array $product
     *
     * @return array y axis array
     */
    public static function createYaxis($product)
    {
		$product['highestPrice'] = round($product['highestPrice'] + $product['lowestPrice'] * 0.1, 2);
		$product['lowestPrice'] = round($product['lowestPrice'] * 0.9, 2);
		
		$priceRange = $product['highestPrice'] - $product['lowestPrice'];
        $highPrice = ceil($product['highestPrice']);
        $lowPrice = floor($product['lowestPrice']);
        if($product['highestPrice'] == $product['lowestPrice']) {
            $highPrice = ceil($highPrice * 1.02);
            $lowPrice = floor($lowPrice * 0.98);
        }

        if($lowPrice == 0) {
            $lowPrice = 0.01;
        }

        $priceSize = 5;
        $priceStep = round($priceRange / $priceSize);
        $priceStep = $priceStep <= 0 ? 1 : $priceStep;

        $yaxis[] = $highPrice;
        if($priceRange == 0 || $priceRange < $priceSize) {
            for($i = $priceSize - 1; $i > 0; $i--) {
                $yaxis[] = '';
            }
        } else {
            for($i = $priceSize - 1; $i > 0; $i--) {
                $value = $lowPrice + $priceStep * $i;
                $yaxis[] = $value <= $lowPrice ? '' : $value;
            }
        }
        $yaxis[] = $lowPrice;

        return $yaxis;
    }

    /**
     * Create x axis
     *
     * @access public
     * @param array $product
     *
     * @return array x axis array
     */
    public static function createXaxis($product)
    {
        $startDay = $product['FirstPriceLog']['log_date'];

        $config = Zend_Registry::get('config');
        $maxDuring = $config['system']['logic']['graphDuringDaysLimit'] ? $config['system']['logic']['graphDuringDaysLimit'] : false;
        //if setting max during days, first point of xaxis will change
        if($maxDuring) {
            $timezone = $config['system']['date']['timezone'] ? $config['system']['date']['timezone'] : 0;
            $today = Zend_Easthv_Date::getNowDate($timezone);
            $limitDay = Zend_Easthv_Date::getBefore(3600 * 24 * $maxDuring, $today);
            $startDay = $startDay > $limitDay ? $startDay : $limitDay;
        }

        $endDay = $product['last_log_date'];
        $diffDays = Zend_Easthv_Date::getDiffDays($startDay,$endDay);
        $xSize = 5;
        $xStep = floor($diffDays / $xSize);
        $xaxis = array();
        $format = $diffDays < 20 ? 'F j' : 'M Y';

        $timezone = $config['system']['date']['timezone'];

        if($diffDays < $xSize){
            $xaxis[] = Zend_Easthv_Date::changeDateByFormat($format, $startDay);
        } else {
            for($i = 1;$i < $xSize;$i++){
                $xaxis[] = Zend_Easthv_Date::getFuture(3600 * 24 * $i * $xStep, $startDay, $format);
            }
        }

        return $xaxis;
    }

    /**
     * Create inline / small size graph
     * $date value should between 0 ~ 100
     *
     * @access public
     * @param int $productid
     * @param array $data
     * @param string $title
     * @param string $mode 1:buy_now | not 1: buy_later
     * @param string $size inline | small
     *
     * @return void
     */
    public static function createInlineGraph($productid, $data, $title, $mode, $size = 'inline')
    {
        if (!$productid || !$data || !$title || $mode != 1 && $mode != 2) {
            throw new Exception('Graph create input incorrect');
        }

        $client = new Zend_Http_Client();
        $client->setUri(self::$_api);
        $client->setMethod(Zend_Http_Client::POST);

        if ($size == 'inline') {
            $width = 124;
            $height = 49;
            $titleSize = '8';
            $topMargin = 5;
            $bottomMargin = 10;
        } else {
            $width = 156;
            $height = 59;        
            $titleSize = '9';
            $topMargin = 8;
            $bottomMargin = 15;
        }

        $bottomMarginRel = floor($bottomMargin / $height * 100);
        $dataHeight = $height - $bottomMargin - $topMargin;
        $dataHeightRel = $dataHeight / $height;
        $dataBase = $bottomMargin / $height * 100;

        foreach($data as $key => $perdata){
            if($perdata == -1) {
                $data[$key] = -1;
                continue;
            }
            $data[$key] = round($perdata * $dataHeightRel + $dataBase, 2);
        }

        $dataBackground = array();
        foreach($data as $perdata){
            $dataBackground[] = 100 - $perdata;
        }
        $dataLen = count($data);

        $colorsBuyNow = array(
            'titleColor' =>    '98CC52',
            'fillColor' =>    '98CC52',
            'fillColorBack' =>    'DAEBC1',
        );

        $colorsBuyLater = array(
            'titleColor' =>    'F05423',
            'fillColor' =>    'F26539',
            'fillColorBack' =>    'FBCCBD',
        );

        $colors = $mode == 1 ? $colorsBuyNow : $colorsBuyLater;

        $titleColor = $colors['titleColor'];
        $backgroundColor = "FFFFFF";
        $fillColor = $colors['fillColor'];
        $fillColorBack = $colors['fillColorBack'];

        $barWidth = $size == 'inline' ? 10 : 13;

        $chart = array(
            'cht' => 'bvs:nda', //Chart Types
            'chtt' => $title, //Chart title
            'chts' => "$titleColor,$titleSize", //Chart title style
            'chbh' => "$barWidth,0,0", //bar width and space
            'chco' => "$fillColor,$fillColorBack", //fill colors
            'chs' => "{$width}x{$height}", //Chart size
            'chd' => "t:" . implode($data, ',') . '|' . implode($dataBackground,','), //chart data
            'chds' => '0,100', //y axis arrange
        );


        /*
        foreach($chart as $key => $c){
            echo "$key=$c\n";
        }
        exit;
         */


        $client->setParameterPost($chart);

        $response = $client->request();

        $path = $size == 'inline' ? self::$savepath['inline'] . 'product_no_' . $productid . '.png' : self::$savepath['small'] . 'product_no_' . $productid . '.png';
        Zend_Easthv_File::writeFile($path,$response->getBody());
    }

    /**
     * Create small size graph
     * 
     *
     * @access public
     * @param int $productid
     * @param array $data
     * @param string $title
     * @param string $mode 1:buy_now | not 1: buy_later
     *
     * @return void
     */
    public static function createSmallGraph($productid, $data, $title, $mode)
    {
        self::createInlineGraph($productid, $data, $title, $mode, 'small');
    }

    /**
     * Create large / medium size graph
     * 
     *
     * @access public
     * @param int $productid
     * @param array $data
     * @param array $points
     * @param string $mode 1:buy_now | not 1: buy_later
     * @param string $size medium | large
     *
     * @return void
     */
    public static function createMediumGraph($productid, $data, $xaxisData, $yaxisData, $points, $mode, $size = 'medium')
    {
        if (!$productid || !$data || !$points || !$xaxisData || !$yaxisData || $mode != 1 && $mode != 2){
            throw new Exception('Graph create input incorrect');
        }

        $client = new Zend_Http_Client();
		
		$client->setConfig(array(
			'maxredirects' => 0,
			'timeout' => 30,
			'useragent' => 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.16) Gecko/20101130 Ubuntu/9.10 (karmic) Firefox/3.5.8',
		));	
		
		$client->setUri(self::$_api);
        $client->setMethod(Zend_Http_Client::POST);



        if ($size == 'medium') {
            $width = 646;
            $height = 208;
            $xFontSize = 14;
            $yFontSize = 11;
            $pointSize = 10;
            $pointInsideSize = 6;
            $topMargin = 25;
            $gridMargin = 41;
            $bottomMargin = 48;
        } else {
            $width = 896;
            $height = 288;
            //$width = 926;
            //$height = 318;
            $xFontSize = 18;
            $yFontSize = 16;
            $pointSize = 12;
            $pointInsideSize = 8;
            $topMargin = 35;
            $gridMargin = 55;
            $bottomMargin = 65;
        }


        $bottomMarginRel = floor($bottomMargin / $height * 100);
        $gridMarginRelx = floor($gridMargin / $width * 100);
        $gridMarginRely = floor($gridMargin / $height * 100);
        $dataHeight = $height - $bottomMargin - $topMargin;
        $dataHeightRel = $dataHeight / $height;
        $dataBase = $bottomMargin / $height * 100;

        $dataShorten = array();
        foreach($data as $perdata){
         // $dataShorten[] = round($perdata * $dataHeightRel + $dataBase, 2);
            $dataShorten[] = round($perdata, 2);
        }

        $xaxis = '-1';
        if($gridMargin > 0) {
            $dataLen = count($dataShorten);
            //repeat first data
            array_unshift($dataShorten,$dataShorten[0]);
            $xOffset = $gridMargin / $width * 100;
            $offsetStep = (100 - $xOffset) / ($dataLen - 1);
            $xaxis = array();
            $xaxis[] = 0;
            for($i = 0; $i < $dataLen; $i++){
                $xaxis[] = round($xOffset + $offsetStep * $i, 3);
            }

            $xaxis[count($xaxis) - 1] = 100;

            foreach($points as $key => $point) {
                $points[$key] = $point + 1;
            }

        }

        /*
        p("xaxis:");
        p($xaxis);
        p("points:");
        p($points);
        p("finalData:");
        p($dataShorten);
         */

        $colorsBuyNow = array(
            'fillColor' =>    '54A4D3',
            'backgroundColor' =>    'D4E6F9',
			'pointColor' => '0279BC',
 			'yTitleColor' => '0279BC',
 			'xTitleColor' => '0279BC',
            'pointInsideColor' => 'FFFFFF',
        );

        $colorsBuyLater = array(
            'fillColor' =>    '54A4D3',
            'backgroundColor' =>    'D4E6F9',
            'pointColor' => 'F26539',
            'pointInsideColor' => 'FFFFFF',
        );

        $colors = $mode == 1 ? $colorsBuyNow : $colorsBuyLater;

        foreach($points as $point){
            $pointsOutside[] = "o,{$colors['pointColor']},0,$point,$pointSize";
            $pointsInside[] = "o,{$colors['pointInsideColor']},0,$point,$pointInsideSize";
        }


        $pointsOutside[] = "B,{$colors['fillColor']}BE,0,0,0";

        $lineColor = 'FFFFFF';
        $backgroundColor = $colors['backgroundColor'];
        $fillColor = $colors['fillColor'];


        $xaxis = $xaxis == '-1' ? $xaxis : implode($xaxis, ',');
        $chart = array(
            'cht' => 'lxy', //Chart Types
            'chxt' => 'x,y', //Chart x,y
            'chxl' => '0:|' . implode($xaxisData,'|') . '|1:|' . implode($yaxisData,'|'), //Chart xaxis and yaxis Title
      	    'chxp' => '0,7,27,47,67,87', //Chart xaxis and yaxis Title
      	    'chxs' => "0,{$colors['xTitleColor']},$xFontSize|1,{$colors['yTitleColor']},$yFontSize", //Chart Axis Label Styles
            'chs' => "{$width}x{$height}", //Chart size
            'chco' => $lineColor, //line color
       //   'chxt' => 'nda', //not show x,y
            'chd' => "t:" . $xaxis  . '|' . implode($dataShorten,','), //chart data
            "chf" => "bg,s,$backgroundColor", //Background
            'chm' => implode($pointsOutside,"|") . '|' . implode($pointsInside,'|'), //points data
            'chg' => '20,50,1,5', //Grid lines
      //    'chg' => "19,100,2,2,$gridMarginRelx,$gridMarginRely", //Grid margins
      	    'chg' => "19,100,2,2,$gridMarginRelx,50", //Grid margins
        );

        $client->setParameterPost($chart);

        $response = $client->request();

        $path = $size == 'medium' ? self::$savepath['medium'] . 'product_no_' . $productid . '.png' : self::$savepath['large'] . 'product_no_' . $productid . '.png';

		Zend_Easthv_File::writeFile($path,$response->getBody());
    }

    /**
     * Create large size graph
     * 
     *
     * @access public
     * @param int $productid
     * @param array $data
     * @param array $points
     * @param string $mode 1:buy_now | not 1: buy_later
     *
     * @return void
     */
    public static function createLargeGraph($productid, $data, $points, $mode)
    {
        self::createMediumGraph($productid, $data, $points, $mode, 'large');
    }

}
